package com.kili.cloud.shorturl.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kili.cloud.common.util.BeanUtils;
import com.kili.cloud.shorturl.controller.config.vo.UrlVo;
import com.kili.cloud.shorturl.repository.UrlMapInfoDao;
import com.kili.cloud.shorturl.repository.entity.UrlMapInfo;
import com.kili.cloud.shorturl.service.ShortUrlFindService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 短链后台接口实现
 * Abner.Hu 2019/08/13
 */

@Service
public class ShortUrlFindServiceImpl implements ShortUrlFindService {

    @Autowired
    UrlMapInfoDao urlMapInfoDao;

    /**
     * 查询所有url
     */
    @Override
    public PageInfo<UrlVo> findAllUrl(UrlVo urlVo) {

        PageInfo pageInfo = new PageInfo<>();
        //开启分页
        Page<UrlVo> page = PageHelper.startPage(urlVo.getPage(),urlVo.getLimit());
        List<UrlMapInfo> allUrl = urlMapInfoDao.selectAllUrl(urlVo);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<UrlVo> urlVoList = new ArrayList<>();
        for(UrlMapInfo info : allUrl){
            UrlVo vo = new UrlVo();
            BeanUtils.copyProperties(info, vo);
            vo.setUrl(info.getShortUrlDomain() + info.getShortUrlUri());
            vo.setShowTime(info.getCreateTime().getTime() / 1000);
            urlVoList.add(vo);
        }

        pageInfo.setList(urlVoList);
        pageInfo.setTotal(page.getTotal());
        pageInfo.setSize(page.getPageSize());

        return pageInfo;


    }

    /**
     * 取消url
     */
    @Override
    public void cancleUrl(UrlVo urlVo) {
        UrlMapInfo urlMapInfo = new UrlMapInfo();
        BeanUtils.copyProperties(urlVo, urlMapInfo);
        urlMapInfo.setIsDeleted(1);
        urlMapInfoDao.updateByPrimaryKeySelective(urlMapInfo);
    }

}
